package com.kevinwu.config;

import com.kevinwu.io.Resources;
import com.kevinwu.pojo.Configuation;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {

    private Configuation configuation;

    public XMLConfigBuilder() {
        this.configuation = new Configuation();
    }

    /**
     * 该方法就是将配置文件解析，封装成Configuation等方法
     * @param inputStream
     * @return
     */
    public Configuation parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {

        //读取字节流，生成Document对象
        Document document = new SAXReader().read(inputStream);
        //获取根节点
        Element rootElement = document.getRootElement();
        //获取所有的property节点
        List<Element> list = rootElement.selectNodes("//property");
        //声明Properties 用于存放 数据库配置信息
        Properties properties = new Properties();
        for (Element element : list) {
            //获取配置文件中数据库配置信息中的项目 name  例如 driverClass
            String name = element.attributeValue("name");
            //获取配置文件中数据库配置信息中的项目 value  例如 com.mysql.jdbc.Driver
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }

        //创建c3p0数据源对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        //将数据源对象设置到configuation对象中
        configuation.setDataSource(comboPooledDataSource);

        //获取所有的业务mapper.xml文件
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            //获取业务mapper.xml文件的绝对路径
            String resource = element.attributeValue("resource");
            //将文件读成字节流存放到内存
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            //解析业务mapper.xml文件 封装到mappedStatement对象中
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuation);
            xmlMapperBuilder.parse(resourceAsStream);
        }

        return  configuation;
    }
}
